<template>
  <div class="content">
    <!--头部-->
    <div class="header-setting">
      <a-breadcrumb class="breadcrumb">
        <a-breadcrumb-item>
          <a href="../main">首页</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>收费管理</a-breadcrumb-item>
        <a-breadcrumb-item>用户管理</a-breadcrumb-item>
      </a-breadcrumb>
      <!--查询条件-->
      <div class="box-condition-body">
        <div class="box-condition-item">
          <div style="margin: 0 50px">注册时间</div>
          <template>
            <div class="button_time">
              <a-button
                type="primary"
                @click="button_time(0)"
                :style="computedStyle(0)"
                >今天</a-button
              >
              <a-button
                type="primary"
                @click="button_time(1)"
                :style="computedStyle(1)"
                >昨天</a-button
              >
              <a-button
                type="primary"
                @click="button_time(2)"
                :style="computedStyle(2)"
                >本周</a-button
              >
              <a-button
                type="primary"
                @click="button_time(3)"
                :style="computedStyle(3)"
                >上周</a-button
              >
              <a-button
                type="primary"
                @click="button_time(4)"
                :style="computedStyle(4)"
                >本月</a-button
              >
            </div>
          </template>
          <template>
            <div style="margin: auto 50px">
              <a-range-picker
                :showTime="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始时间', '结束时间']"
                @ok="onOk"
                @change="onChange"
                :value="rangePicker()"
              />
            </div>
          </template>
        </div>
        <div class="box-condition-item">
          <div style="margin: 0 50px">车牌号</div>
          <template>
            <a-input
              style="margin: 0 100px 0 0px; width: 200px"
              v-model="inputPlate"
              placeholder="车牌号"
            />
          </template>
          <div style="margin: 0 50px">电话号</div>
          <template>
            <a-input
              style="margin: 0 100px 0 0px; width: 200px"
              v-model="inputPhone"
              placeholder="电话号"
            />
          </template>
        </div>
        <div class="box-condition-item">
          <div style="margin: 0 50px">用户名</div>
          <template>
            <a-input
              style="margin: 0 100px 0 0px; width: 200px"
              v-model="inputNickName"
              placeholder="用户名"
            />
          </template>
          <div style="margin: 0 50px">巡查员</div>
          <template>
            <a-select
              style="margin: 0 100px 0 0px; width: 200px"
              class="text-value"
              showSearch
              placeholder="选择巡查员"
              v-model="nick"
              :allowClear="allowClear"
            >
              <a-select-option v-for="p in user" :key="p.id" :value="p.name">
                {{ p.name }}
              </a-select-option>
            </a-select>
          </template>

          <div class="select-box">
            <a-button icon="search" type="primary" @click="selecDuate"> 查询 </a-button>
            &nbsp;
            <a-button icon="sync" @click="reset"> 重置 </a-button>
          </div>
        </div>
      </div>
    </div>

    <div class="box-form">
      <!--工具栏-->
      <div class="box-tool">
        <div></div>
        <div style="display: flex">
          <a-button type="primary" @click="exportFile()">导出 </a-button>
        </div>
      </div>
      <!--数据表格-->
      <div class="box-table">
        <a-table
          :columns="columns"
          :dataSource="dataSource"
          :pagination="pagination"
          bordered
          size="small"
          :scroll="scroll"
          :customRow="customRow"
          :rowClassName="setRowClassName"
          @change="queryPageData"
        >
          <template slot="balanceSlot" slot-scope="text">
            <div>{{ text == undefined || text == "" ? text : text / 100 }}</div>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import UserManagerApi from "../../api/operate/UserManager";
import { Loading } from "element-ui";

const columns = [
  {
    title: "序号",
    dataIndex: "no",
    width: "5%",
  },
  {
    title: "车牌号",
    dataIndex: "licencePlate",
    width: "10%",
  },
  {
    title: "电话",
    dataIndex: "phoneNum",
    width: "10%",
  },
  {
    title: "客户账号",
    dataIndex: "account",
    width: "10%",
  },
  {
    title: "账号活动余额(元)",
    dataIndex: "balance",
    scopedSlots: { customRender: "balanceSlot" },
    width: "10%",
  },
  {
    title: "客户名称",
    dataIndex: "nickName",
    width: "10%",
  },
  {
    title: "推荐人",
    dataIndex: "nick",
    width: "10%",
  },
  {
    title: "注册时间",
    dataIndex: "createdTime",
    width: "10%",
  },
];
const dataSource = [];
const queryCondition = {
  limit: 10,
  curr: 1,
  plate: "",
  phone: "",
  nickName: "",
  nick: "",
  timeScreenCondition: 6,
  startTimeStamp: "",
  endTimeStamp: "",
};
export default {
  name: "UserManager",
  /*数据层*/
  data() {
    return {
      parks: [],
      selectId: -1,
      momentArr: [],
      columns: columns,
      dataSource: dataSource,
      /*分页插件*/
      pagination: {
        showTotal: (total) => `共${total}条`,
        total: 0, // set get
        defaultCurrent: 1,
        showQuickJumper: true,
        defaultPageSize: 10,
      },
      /*表格固定头部*/
      scroll: {
        y: 550,
      },
      tableState: {
        rowId: -1,
      },
      /*当前选中的行数据*/
      currRowData: "",
      queryCondition,
      inputPlate: "",
      inputNickName: "",
      inputPhone: "",
      nick: "",
      balance: "",
      allowClear: true,
      user: [],
    };
  },
  /*方法层*/
  methods: {
    /*时间按钮控制*/
    button_time(e) {
      this.selectId = e;
      let momentStart;
      let momentEnd;
      switch (e) {
        case 0:
          momentStart = moment().startOf("day");
          momentEnd = moment().endOf("day");
          break;
        case 1:
          momentStart = moment().add("day", -1).startOf("day");
          momentEnd = moment().add("day", -1).endOf("day");
          break;
        case 2:
          momentStart = moment().week(moment().week()).startOf("week");
          momentEnd = moment().week(moment().week()).endOf("week");
          break;

        case 3:
          momentStart = moment()
            .week(moment().week() - 1)
            .startOf("week");
          momentEnd = moment()
            .week(moment().week() - 1)
            .endOf("week");
          break;
        case 4:
          momentStart = moment().month(moment().month()).startOf("month");
          momentEnd = moment().month(moment().month()).endOf("month");
          break;
        default:
          break;
      }
      this.momentArr[0] = momentStart;
      this.momentArr[1] = momentEnd;
      this.getUser();
      this.queryData();
    },

    /*日期选择*/
    onChange(date) {
      this.selectId = -1;
      this.momentArr = date;
    },
    onOk() {
      this.selectId = -1;
      this.queryData();
    },

    rangePicker() {
      return this.momentArr;
    },
    /*表格*/
    customRow(record) {
      return {
        on: {
          // 事件
          click: () => {
            this.currRowData = record;
            this.tableState.rowId = record.id;
          }, // 点击行
        },
      };
    },

    setRowClassName(record) {
      return record.id === this.tableState.rowId ? "clickRowStyl" : "";
    },

    /* ---------------------------- 页面数据 ---------------------------- */
    queryPageData(page) {
      this.queryData(page.current);
    },
    exportFile() {
      let q = this.dealQueryCondition();
      UserManagerApi.exportExcel(q)
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });
          let fileName = decodeURIComponent(res.headers.filename);
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", `${fileName}`);
          link.click();
        })
        .catch((err) => {
          let data = err.data;
          if (data) {
            return this.$message.warn(data);
          }
          console.log("导出记录异常！", err);
        });
    },
    dealQueryCondition() {
      let condition = this.queryCondition;
      let beginMoment = this.momentArr[0];
      let endMoment = this.momentArr[1];
      if (beginMoment != undefined && endMoment != undefined) {
        condition.startTimeStamp = new Date(beginMoment).getTime() / 1000;
        condition.endTimeStamp = new Date(endMoment).getTime() / 1000;
        condition.timeScreenCondition = 6;
      } else {
        condition.timeScreenCondition = 0;
      }
      condition.plate = this.inputPlate;
      condition.phone = this.inputPhone;
      condition.nickName = this.inputNickName;
      condition.nick = this.nick;

      return condition;
    },

    queryData(pageNum) {
      let condition = this.dealQueryCondition();
      condition.curr = pageNum || 1;

      this.loading && this.loading.close(); // 这里是为了防止还没有请求结束（loading未关闭）再次连续触发
      this.loading = Loading.service({
        // 这里可以直接使用选择器名称，当然也可以用ref获取DOM结构，可以提前把DOM结构缓存起来，这样频繁被触发的时候是不是就不会重新获取DOM了呢？好像可以提升一丢丢性能吧（个人理解）
        target: ".content",
      });

      UserManagerApi.getUserInfoList(condition)
        .then((data) => {
          let { list, pageNum, pageSize, total } = data.data;
          let array = list || [];
          array = array.map((item, index) => {
            return { ...item, no: total - (pageNum - 1) * pageSize - index };
          });
          this.pagination.total = total;
          this.dataSource = array;
          this.loading.close();
        })
        .catch((error) => {
          this.dataSource = ["数据加载异常"];
          console.log("获取注册用户数据异常！", error);
        });
    },
    getUser() {
      UserManagerApi.getManagerList()
        .then((res) => {
          console.log(res.data);
          this.user = res.data;
        })
        .catch((err) => {
          this.$message.error("获取管理人失败:" + err);
        });
    },

    selecDuate() {
      this.queryData();
    },
    reset() {
      this.inputPlate = "";
      this.inputPhone = "";
      this.inputNickName = "";
      this.nick = "";
      this.button_time(0);
    },
  },
  /*计算层*/
  computed: {
    computedStyle() {
      return function (selectId) {
        return this.selectId == selectId ? "" : "";
      };
    },
  },
  /*渲染层*/
  mounted() {
    this.button_time(0);
  },
};
</script>

<style scoped>
.content {
  width: 100%;
  height: 100%;
}

.header-setting {
  width: 100%;
  height: auto;
  background: #fff;
}

.header-setting .breadcrumb {
  margin-left: 41px;
  padding-top: 15px;
}

/*表格行选中背景颜色*/
.clickRowStyl {
  background-color: #c1e0fd;
}

.box-condition-item {
  display: flex;
  align-items: center;
  min-width: 1500px;
  margin-top: 5px;
  margin-bottom: 5px;
  padding: 5px 0;
}

.box-condition-item .box-item {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 5px 5px 20px 5px;
}

.button_time button {
  margin-left: 10px;
}

/* 表单 */
.box-form {
  padding-left: 40px;
  padding-right: 40px;
  min-height: 705px;
  background: #fff;
  margin-top: 8px;
}

.box-form .box-tool {
  padding-top: 11px;
  margin: 8px 0;
  width: 100%;
  /* flex */
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.select-box {
  margin-left: 20px;
}
</style>

